package com.dc.web.controller;


import com.dc.constant.Constants;
import com.dc.dao.AlarmDao;
import com.dc.entity.AlarmEntity;
import com.dc.exception.ServiceException;
import com.dc.model.AjaxResult;
import com.dc.model.AlarmUpdateBody;
import com.dc.model.PageListBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Optional;

@RestController
@RequestMapping("/api/alarm")
@Slf4j
public class AlarmController {

    @Resource
    AlarmDao alarmDao;

    @GetMapping()
    public AjaxResult getAlarm(PageListBody body, Integer complete) {

        Integer pageNumber = body.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = body.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);

        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);

        Page<AlarmEntity> result = null;

        if(ObjectUtils.isNotEmpty(complete)) {
            AlarmEntity bean = new AlarmEntity();
            bean.setComplete(complete);
            Example<AlarmEntity> example = Example.of(bean);
            result = alarmDao.findAll(example, pageRequest);
        } else {
            result = alarmDao.findAll(pageRequest);
        }

        return AjaxResult.success(result);
    }

    @PutMapping("/{id}")
    public AjaxResult updateAlarm(@PathVariable("id") Long id, @RequestBody AlarmUpdateBody body) {

        Optional<AlarmEntity> optionalAlarm = alarmDao.findById(id);
        if(!optionalAlarm.isPresent()) {
            throw new ServiceException("更新的预警不存在");
        }
        AlarmEntity alarm = optionalAlarm.get();
        if(Constants.COMPLATE_YES.equals(alarm.getComplete())) {
            throw new ServiceException("已经处理的预警不可以重复处理");
        }
        alarm.setReason(body.getReason());
        alarm.setImprovePlan(body.getImprovePlan());
        alarm.setComplete(Constants.COMPLATE_YES);

        AlarmEntity save = alarmDao.save(alarm);

        return AjaxResult.success(save);
    }
}
